const SONG_NAME = "未来へ";
const DIC_URL = "kuromoji/dict/";
const LYRIC_PATH = "/lyrics_data/";

let tokenizer = null;

const vm = new Vue({
  el: "#app",
  data: {
    isLoaded: false,
    lyricData: {},
    lyricList: [],
    btnData: {
      showKana: true, // 假名
      showChinese: true, // 中文
    }

  },
  methods: {

    tokenize: function (text) {
      if (this.text == "" || this.tokenizer == null) {
        return [];
      }
      try {
        return this.tokenizer.tokenize(text);
      } catch (e) {
        console.log(e);
        return [];
      }
    },

    /** 片假名转平假名 */
    katakanaToHiragana: function (text) {
      if (!text) return "";
      return text.replace(/[\u30a1-\u30f6]/g, function (match) {
        const chr = match.charCodeAt(0) - 0x60;
        return String.fromCharCode(chr);
      });
    },

    /** 将歌词数据渲染为注音标签 */
    renderTag: function (lyricObj) {
      if (!lyricObj) return;

      let html = '';
      // 日文歌词
      const lyricJP = lyricObj.lyric;

      // 获取分词数据
      const tokens = this.tokenize(lyricJP);

      // 遍历分词结果
      for (const token of tokens) {
        if (this.hasKanji(token.surface_form)) {
          // 包含汉字的场合，拼接ruby注音标签
          html += `<ruby class="ruby">${token.surface_form}<rt class="rt">${this.katakanaToHiragana(token.pronunciation)}</rt></ruby>`;
        } else {
          // 不包含汉字，直接拼接
          html += token.surface_form;
        }
      }
      return html;
    },

    /** 判断字符串是否包含汉字 */
    hasKanji: function (str) {
      const codePoints = [...str].map(c => c.codePointAt(0));
      return codePoints.some(cp =>
        (cp >= 0x4E00 && cp <= 0x9FFF) ||
        (cp >= 0x3400 && cp <= 0x4DBF) ||
        (cp >= 0xF900 && cp <= 0xFAFF) ||
        (cp >= 0x20000 && cp <= 0x2A6DF)
      );
    },

    /** 获取歌词数据 */
    getLyrics(filename) {
      const requestPath = `${LYRIC_PATH}${filename}.json`;
      return new Promise((resolve, reject) => {
        fetch(requestPath)
        .then(response => response.json())
        .then(data => {
          this.lyricData = data;
          resolve(data);
        })
        .catch(error => {
          console.log(error)
          reject(error);
        })
      })
      
    },
    /** 初期化分词器 */
    initTokenizer() {
      return new Promise((resolve, reject) => {
        kuromoji.builder({ dicPath: DIC_URL }).build(function (error, _tokenizer) {
          if (error != null) {
            console.log(error);
            reject(error);
          }
          this.isLoading = false;
          resolve(_tokenizer);
        });
      })
    },
    /** 显示/隐藏假名 */
    jpBtnClick() {
      const currShowKana = !this.btnData.showKana;
      this.btnData.showKana = currShowKana;
      // 操作dom，显示/隐藏假名
      const rts = document.querySelectorAll(".rt");
      rts?.forEach(rt => {
        rt.style.display = currShowKana ? "ruby-text" : "none";
      });
    },
    /** 显示/隐藏中文 */
    zhBtnClick() {
      this.btnData.showChinese = !this.btnData.showChinese;
    }

  },
  async mounted() {
    // 初始化分词器
    this.tokenizer = await this.initTokenizer();
    // 获取歌词内容
    const lyricsData = await this.getLyrics(SONG_NAME);
    for (const lyric of lyricsData.lyrics) {
      // 将歌词内容转为标注标签
      this.lyricList.push({
        lyricJP: this.renderTag(lyric),
        lyricZH: lyric.zh
      }); 
    }
    // 设置title
    document.title = lyricsData.songName;
    // 初始化完成
    this.isLoaded = true;
    console.log(this.$refs);
  }
});




